package edu.biwu.advice;

import edu.biwu.utils.TransactionManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author 王俊彪
 * @version 1.0
 */
@Component
@Aspect
public class TransactionAdvice {
    @Autowired
    TransactionManager transactionManager;
    private Logger logger = LogManager.getLogger(TransactionAdvice.class);

    @Around("execution( * edu.biwu.service..*.*(..)) && !execution( * edu.biwu.service..*.find*(..))")
    public void aroundServiceAdvice(ProceedingJoinPoint pjp){
        try {
        transactionManager.beginTransaction();
            logger.info("开启事务");
            logger.info("执行{}的目标方法",pjp.getSignature());

            pjp.proceed();

            transactionManager.commit();
            logger.info("提交事物");
        } catch (Throwable e) {
            transactionManager.rollBack();
            logger.info("回滚事务");
            throw new RuntimeException(e);

        } finally {
            transactionManager.release();
            logger.info("释放资源");
        }
    }
}
